package com.travel.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.travel.entity.Hotel;
import com.travel.entity.HotelFavorite;
import com.travel.entity.ScenicFavorite;
import com.travel.service.HotelService;
import com.travel.service.impl.HotelFavoriteServiceImpl;
import com.travel.service.impl.HotelServiceImpl;
import com.travel.util.PageInfo;

/**
 * Servlet implementation class HotelController
 */
@WebServlet("/HotelServlet")
@MultipartConfig // 表示该控制器支持文件上传
public class HotelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
     
	// 引入HotelService
	HotelService hotelService = new HotelServiceImpl();
	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HotelServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
		// 控制器如何获取请求携带的参数?
		String op = request.getParameter("op");	
		if ("queryAllHotel".equals(op)) {
			// 查询列表
			doQueryAllHotelList(request, response);
		} else if ("searchByPage".equals(op)) {
			doFindHotelByPage(request, response);
		} else if ("delete".equals(op)) {
			doDeleteHotelById(request, response);
		} else if ("getHotelById".equals(op)) {
			doGetHotelById(request, response);
		} else if("modify".equals(op)) {
			// 修改
			doModify(request, response);
		} else if("insertHotel".equals(op)) {
			// 修改
			doInsertHotel(request, response);
		} else if("insertGallery".equals(op)) {
			// 修改
			doInsertGallery(request, response);
		}
		
		
	}

	
	private void doInsertGallery(HttpServletRequest request, HttpServletResponse response) {
		
		int hotelId = Integer.parseInt(request.getParameter("hotelId"));
		int userId=Integer.parseInt(request.getParameter("userId"));
		List<HotelFavorite> hotelFavoriteList = new HotelFavoriteServiceImpl().queryFavoriteListByUserIdAndHotelId(userId, hotelId);
		
		
		System.out.println("根据用户Id和酒店Id得到的列表" + hotelFavoriteList);
		if (hotelFavoriteList.size()==0) {
			
			HotelFavorite scenicFavorite=new HotelFavorite(null, userId, hotelId,null,null);
			boolean insert = new HotelFavoriteServiceImpl().insert(scenicFavorite);
			if (insert) {
				try {
					response.getWriter().print("success");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}else {
			System.out.println(2);
			try {
				response.getWriter().print("fail");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void doQueryAllHotelList(HttpServletRequest request, HttpServletResponse response) {

		// 调用业务层
		List<Hotel> hotelList = hotelService.queryAllHotels();
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json;
		try {
			json = objectMapper.writeValueAsString(hotelList);
			System.out.println(hotelList);
			// 设置响应内容类型
			response.setContentType("application/json;charset=utf-8");
			// 响应数据
			PrintWriter out= response.getWriter();
			out.print(json);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void doFindHotelByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		int pageNum = Integer.parseInt(request.getParameter("pageNum"));
		
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		String hotelName = request.getParameter("keyword");
		
		if (hotelName==null) {
			hotelName="";
		}
		
		PageInfo<Hotel> pageInfo = hotelService.queryByPageAndName(pageNum, pageSize,hotelName);
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(pageInfo);
		System.out.println(json);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter  out= response.getWriter();
		out.print(json);
	}
	

	private void doDeleteHotelById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		System.out.println("doDeleteHotelById方法被执行");
		// 调用业务层
		String hotelId = request.getParameter("hotelId");
		System.out.println(hotelId);
		if (hotelId == null) {
			return;
		}
		hotelService.deleteFromTabHotelSuccesOrNot(Integer.parseInt(hotelId));
		// 再次一次查询分页结果
		int pageNum = Integer.parseInt(request.getParameter("pageNum"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		String hotelName = request.getParameter("keyword");
		PageInfo<Hotel> pageInfo = hotelService.queryByPageAndName(pageNum, pageSize,hotelName);
		// 封装数据
	    ObjectMapper objectMapper = new ObjectMapper();
	    String json = objectMapper.writeValueAsString(pageInfo);
	    // 设置响应内容类型
	    response.setContentType("application/json;charset=utf-8");
	    // 响应数据
	    PrintWriter  out= response.getWriter();
	    out.print(json);
	}

	private void doGetHotelById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		System.out.println("doGetHotelById方法被执行");
		String hotelId = request.getParameter("hotelId");
		System.out.println(hotelId);
		if (hotelId == null) {
			return;
		}
		List<Hotel> list = hotelService.queryHotelById(Integer.parseInt(hotelId));
		
		// 封装数据
	    ObjectMapper objectMapper = new ObjectMapper();
	    String json = objectMapper.writeValueAsString(list);
	    // 设置响应内容类型
	    response.setContentType("application/json;charset=utf-8");
	    // 响应数据
	    PrintWriter  out= response.getWriter();
	    out.print(json);
	}
	
	private void doModify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		System.out.println("执行了HotelServlet中的doModify方法");
		
		// 获取普通组件
		String hotelId = request.getParameter("modal-hotelId");
		String hotelName = request.getParameter("modal-hotelName");
		String hotelDesc = request.getParameter("modal-hotelDesc");
		String hotelPhone = request.getParameter("modal-hotelPhone");
		String hotelAddress = request.getParameter("modal-hotelAddress");
		String hotelStar = request.getParameter("modal-hotelStar");
		
		// 获取单个文件
		Part part = request.getPart("modify-hotel-picture");
		
		// 判断用户是否有上传文件
		if (part.getSize() == 0) {
			// 调用业务层 编辑hotel
			Hotel hotel = new Hotel(Integer.parseInt(hotelId), hotelName, hotelDesc, null, hotelPhone, hotelAddress, hotelStar);
			
			boolean modify = hotelService.modifyHotelSuccessOrNot(hotel);
			if (modify) {
			    // 响应数据
			    PrintWriter  out= response.getWriter();
			    out.print("success");
			    response.sendRedirect("back/hotel-management.jsp");
			}
			System.out.println("用户有上传文件");
		} else {
			System.out.println("有上传的图片");
			// 有上传酒店的图片
			// 对上传的文件类型进行效验
			String allowImgType = "image/jpg,image/jpeg,image/png,image/gif";
			// 获取当前文件的内容类型
			String contentType = part.getContentType();
			if (allowImgType.indexOf(contentType) == -1) {
				// 文件类型不匹配
				System.out.println("上传文件类型不匹配");
				// 重定向注册页面,提示文件格式错误
//					response.sendRedirect("front/register.jsp?fileuploaderror=notallowtype");
				return;
			}else {
				// 获取上传的真实文件名
				String realFileName = part.getSubmittedFileName();
				// 保证文件名唯一
				// 时间戳
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
				String time = formatter.format(now);
				// 4位随机数
				int random = (int)((Math.random()*9+1)*1000);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(time).append(random).append(realFileName);
				
				// 定义文件存储目录
				File file = new File("D:\\image\\hotel");
				
				StringBuffer filePath = new StringBuffer();
				
				filePath.append(file.getPath()).append(File.separator).append(fileName);
				
				// 将文件写入指定位置
				part.write(filePath.toString());
				
				// 调用业务逻辑层
				Hotel hotel = new Hotel(Integer.parseInt(hotelId), hotelName, hotelDesc,fileName.toString(), hotelPhone, hotelAddress, hotelStar);
				System.out.println(hotel);
				System.out.println("上传的fileName文件名为" + fileName.toString());
				hotelService.modifyHotelWithHotelPictureSuccessOrNot(hotel);   // 将修改的
				System.out.println("修改带hotelPicture成功");
				response.sendRedirect("back/hotel-management.jsp");
				}
			}
	}
	


	/**
	 * 新增酒店的方法
	 * @param request
	 * @param response
	 * @throws ServletException 
	 * @throws IOException 
	 */
	private void doInsertHotel(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		// 获取普通组件
		String hotelName = request.getParameter("hotelName");
		String hotelDesc = request.getParameter("hotelDesc");
		String hotelPhone = request.getParameter("hotelPhone");
		String hotelAddress = request.getParameter("hotelAddress");
		String hotelStar = request.getParameter("hotelStar");
		
		// 获取单个文件
		Part part = request.getPart("hotelPicture");
	
		// 判断用户是否有上传文件
		if (part.getSize() == 0) {
			// 调用业务层 编辑hotel
			Hotel hotel = new Hotel(null, hotelName, hotelDesc, null, hotelPhone, hotelAddress, hotelStar);
			
			boolean modify = hotelService.insertTalHotelSuccesOrNot(hotel);
			if (modify) {
			    // 响应数据
			    PrintWriter out= response.getWriter();
			    out.print("success");
			}
			System.out.println("用户有上传文件");
		} else {
			System.out.println("有上传的图片");
			// 有上传酒店的图片
			// 对上传的文件类型进行效验
			String allowImgType = "image/jpg,image/jpeg,image/png,image/gif";
			// 获取当前文件的内容类型
			String contentType = part.getContentType();
			if (allowImgType.indexOf(contentType) == -1) {
				// 文件类型不匹配
				System.out.println("上传文件类型不匹配");
				// 重定向注册页面,提示文件格式错误
	//			response.sendRedirect("front/register.jsp?fileuploaderror=notallowtype");
				return;
			}else {
				// 获取上传的真实文件名
				String realFileName = part.getSubmittedFileName();
				// 保证文件名唯一
				// 时间戳
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
				String time = formatter.format(now);
				// 4位随机数
				int random = (int)((Math.random()*9+1)*1000);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(time).append(random).append(realFileName);
				
				// 定义文件存储目录
				File file = new File("D:\\image\\hotel");
				
				StringBuffer filePath = new StringBuffer();
				
				filePath.append(file.getPath()).append(File.separator).append(fileName);
				
				// 将文件写入指定位置
				part.write(filePath.toString());
				
				// 调用业务逻辑层
				Hotel hotel = new Hotel(null, hotelName, hotelDesc,fileName.toString(), hotelPhone, hotelAddress, hotelStar);
				System.out.println(hotel);
				System.out.println("上传的fileName文件名为" + fileName.toString());
				hotelService.insertTalHotelSuccesOrNot(hotel);   // 将修改的
				
				System.out.println("修改带hotelPicture成功");
				response.sendRedirect("back/hotel-management.jsp");
				}
			}
		}


}
